/* eslint-disable */
import { ObjectDirective } from 'vue';
import { ElMessage } from 'element-plus';
import Clipboard from 'clipboard';

if (!Clipboard) {
  throw new Error('you should npm install `clipboard` --save at first ');
}

const handleClipboard: ObjectDirective<any, string> = {
  mounted(el, binding) {
    if (binding.arg === 'success' || binding.arg === 'error') {
      el[`$$clipboard_${binding.arg}`] = binding.value;
    } else { // cut or copy or undefined
      const clipboard = new Clipboard(el, {
        text: () => binding.value,
        action() { return binding.arg === 'cut' ? 'cut' : 'copy'; },
      });
      clipboard.on('success', e => {
        const callback = el.$$clipboard_success;
        if (callback) {
          callback(e);
          return;
        }
        ElMessage.success('复制成功!');
      });
      clipboard.on('error', e => {
        const callback = el.$$clipboard_error;
        if (callback) {
          callback(e);
          return;
        }
        ElMessage.error('复制失败!');
      });
      el.$$clipboard = clipboard;
    }
  },
  updated(el, binding) {
    if (binding.arg === 'success' || binding.arg === 'error') {
      el[`$$clipboard_${binding.arg}`] = binding.value;
    } else {
      el.$$clipboard.text = function () { return binding.value; };
      el.$$clipboard.action = function () { return binding.arg === 'cut' ? 'cut' : 'copy'; };
    }
  },
  unmounted(el, binding) {
    if (binding.arg === 'success' || binding.arg === 'error') {
      delete el.$$clipboard_success;
      delete el.$$clipboard_error;
    } else {
      el.$$clipboard.destroy();
      delete el.$$clipboard;
    }
  },
};

export default handleClipboard;
